package com.avcdata.aoscustommade.activity;

import android.content.Intent;
import android.text.SpannableString;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.avcdata.aoscustommade.R;
import com.avcdata.aoscustommade.main.BaseActivity;
import com.avcdata.aoscustommade.model.ChangePhoneOrEmailModel;
import com.avcdata.aoscustommade.presenter.ChangePhoneOrEmailPresenter;
import com.avcdata.aoscustommade.utils.AppActivityManager;
import com.avcdata.aoscustommade.utils.SharedPreferencesUtils;
import com.avcdata.aoscustommade.utils.TextUitl;
import com.avcdata.aoscustommade.utils.ToastUtils;
import com.avcdata.aoscustommade.view.ChangePhoneOrEmailView;
import com.avcdata.aoscustommade.view.TimeCount;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;

import org.json.JSONException;
import org.json.JSONObject;


import static com.avcdata.aoscustommade.utils.ToastUtils.showShortSnackBar;


/**
 * Created by c.c on 2017/2/28.
 * 修改账号
 */

public class ChangePhoneOrEmail_Activity extends BaseActivity implements ChangePhoneOrEmailView {
    @ViewInject(R.id.leftImage)
    private ImageView leftImage;
    @ViewInject(R.id.leftText)
    private TextView leftText;
    @ViewInject(R.id.title)
    private TextView title;
    @ViewInject(R.id.changephone_end)
    private EditText changephone_end;
    @ViewInject(R.id.changephone_new)
    private EditText changephone_new;
    @ViewInject(R.id.changephone_code)
    private EditText changephone_code;
    @ViewInject(R.id.changephone_codebtn)
    private Button changephone_codebtn;
    @ViewInject(R.id.confrim)
    private Button confrim;

    private boolean type = true;
    private TimeCount timeCount;
    private SharedPreferencesUtils sp;
    private ChangePhoneOrEmailPresenter changePhoneOrEmailPresenter;


    @Override
    public void initView() {
        setContentView(R.layout.activity_changephone);
        AppActivityManager.getAppManager().addActivity(this);
        ViewUtils.inject(this);

    }

    @Override
    public void initInstall() {
        sp = new SharedPreferencesUtils(this);
        type = TextUitl.isPhone(sp.getUserAccount());
        SpannableString s;
        if (type) {
            title.setText("修改手机号");
            changephone_end.setText(sp.getUserAccount());
//            changephone_end.setText(TextUitl.phoneHide(sp.getUserAccount()));
            s = new SpannableString("请输入新手机号");

        } else {
            title.setText("修改邮箱号");
            changephone_end.setText(sp.getUserAccount());
            s = new SpannableString("请输入新邮箱号");
        }
        changephone_new.setHint(s);
        timeCount = new TimeCount(this, changephone_code, changephone_codebtn, 60000, 1000);
        changephone_end.setFocusable(false);
        changephone_end.setFocusableInTouchMode(false);
        changephone_end.setEnabled(false);

        changePhoneOrEmailPresenter = new ChangePhoneOrEmailPresenter(this, new ChangePhoneOrEmailModel(ChangePhoneOrEmail_Activity.this));
    }


    @Override
    public void initData() {

    }

    @Override
    public void evenControl() {
        leftImage.setOnClickListener(this);
        leftText.setOnClickListener(this);
        changephone_codebtn.setOnClickListener(this);
        confrim.setOnClickListener(this);

    }

    @Override
    public void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.leftImage:
            case R.id.leftText:
                AppActivityManager.getAppManager().finishActivity(this);
                break;
            case R.id.changephone_codebtn:
                if (checkNewPhone(changephone_new)) {
                    if (changephone_codebtn.getText().toString().trim().equals("重新获取")) {
                        changephone_code.setText("");
                    }
                    loadCode();
                }
                break;
            case R.id.confrim:
                if (checkNewPhone(changephone_new) && isEqualsPhone()) {
                    loadCheckCode();
                }

                break;

        }

    }

//
//    /**
//     * 检验手机号是否存在
//     */
//    private void loadCheackAccount() {
//        String url = AvcConstants.URLHeaderUserinfo;
//        if (TextUitl.isPhone(TextUitl.getString(changephone_end))) {
//            url = url + "isExists?type=iphone&keyWord="+TextUitl.getString(changephone_new);
//        } else {
//            url = url + "isExists?type=email&keyWord="+TextUitl.getString(changephone_new);
//        }
//
//        HttpUtil.get(ChangePhoneOrEmail_Activity.this,url,new JsonHttpResponseHandler(){
//            private String message;
//
//            @Override
//            public void onStart() {
//                super.onStart();
//            }
//
//            @Override
//            public void onSuccess(int i, JSONObject jsonObject) {
//                super.onSuccess(i, jsonObject);
//                Log.e("event", "请求判断是否有这个账号成功了----" + jsonObject);
//                try {
//                    if (!TextUitl.isEmpty(jsonObject.toString())) {
//                        boolean returnValue = jsonObject.getBoolean("returnValue");
//                        message = jsonObject.getString("message").trim();
//                        if (returnValue) {
//                            loadCheckCode();
//                        } else {
//                            T.showShort(ChangePhoneOrEmail_Activity.this, "该账号不存在");
//                        }
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public void onFailure(Throwable throwable, JSONObject jsonObject) {
//                super.onFailure(throwable, jsonObject);
//                Log.e("event", "请求判断是否有这个账号失败了----" + jsonObject);
//                loadedType(false, message,-1);
//
//            }
//
//        });
//
//    }


    /**
     * 获取验证码
     */
    private void loadCode() {
        timeCount.start();
        changePhoneOrEmailPresenter.lodeCode(type, TextUitl.getString(changephone_new));

    }

    //获取验证码成功
    @Override
    public void loadCodeSuccess(JSONObject jsonObject) {
        try {
            if (!TextUitl.isEmpty(jsonObject.toString())) {
                boolean success = jsonObject.getBoolean("success");
                String message = jsonObject.getString("message").trim();
                if (success) {
                    ToastUtils.showShort(ChangePhoneOrEmail_Activity.this, "验证码已发送");
                } else {
                    loadedType(false, message, -1);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //获取验证码失败
    @Override
    public void loadCodeFailure() {
        loadedType(false, "", -1);
    }


    /**
     * 验证验证码
     */
    private void loadCheckCode() {
        String telephone = TextUitl.getString(changephone_new);
        String code = TextUitl.getString(changephone_code);
        changePhoneOrEmailPresenter.loadCheckCode(telephone, code);
    }

    //验证验证吗成功
    @Override
    public void loadCheckCodeSuccess(JSONObject jsonObject) {
        try {
            if (!TextUitl.isEmpty(jsonObject.toString())) {
                boolean success = jsonObject.getBoolean("success");
                String message = jsonObject.getString("message").trim();
                if (success && jsonObject.has("returnValue")) {
                    String returnValue = jsonObject.getString("returnValue").trim();
                    if (!TextUitl.isEmpty(returnValue) && !returnValue.equals("{}")) {
                        JSONObject returnValueObject = new JSONObject(returnValue);
                        String result = returnValueObject.getString("result").trim();
                        message = returnValueObject.getString("message").trim();
                        if (!TextUitl.isEmpty(result) && result.equals("3")) {
                            loadedType(true, message, 0);
                        } else {
                            loadedType(false, message, -1);
                        }
                    } else {
                        loadedType(false, message, -1);
                    }
                } else {
                    loadedType(false, message, -1);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //验证验证码失败
    @Override
    public void loadCheckCodeFailure() {
        loadedType(false, "", -1);
    }


    /**
     * 账号重置
     */
    private void loadReset() {
        String oldName = TextUitl.getString(changephone_end);
        String newName = TextUitl.getString(changephone_new);

        changePhoneOrEmailPresenter.loadReset(type, oldName, newName);
    }

    //账号重置成功
    @Override
    public void loadResetSuccess(JSONObject jsonObject) {
        try {
            if (!TextUitl.isEmpty(jsonObject.toString())) {
                boolean success = jsonObject.getBoolean("success");
                String message = jsonObject.getString("message").trim();
                if (success) {
                    sp.setUserAccount(TextUitl.getString(changephone_new));
                    sp.setUserPassword("");
                    loadedType(true, message, 1);
                } else {
                    loadedType(false, message, -1);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //账号重置失败
    @Override
    public void loadResetFailure() {
        loadedType(false, "", -1);
    }

    /**
     * 结果处理
     *
     * @param isSuccess
     * @param message
     */
    private void loadedType(boolean isSuccess, String message, int num) {
        if (isSuccess) {
            if (num == 0) {
                loadReset();
            } else {
                ToastUtils.showShort(ChangePhoneOrEmail_Activity.this, "账号修改成功");
                Intent intent = new Intent(ChangePhoneOrEmail_Activity.this, Login_Activity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        } else {
            if (TextUitl.isEmpty(message)) {
                ToastUtils.showShort(ChangePhoneOrEmail_Activity.this, "网络请求错误");
                return;
            }
            ToastUtils.showShort(ChangePhoneOrEmail_Activity.this, message);
        }

    }


    /**
     * 验证新输入账户
     *
     * @return
     */
    private boolean checkNewPhone(EditText editText) {
        if (TextUitl.isEmpty(TextUitl.getString(editText))) {
            if (type) {
                showShortSnackBar(this, "请输入新手机号");
            } else {
                showShortSnackBar(this, "请输入新邮箱号");
            }
            return false;
        } else {
            if (type) {
                if (TextUitl.isPhone(TextUitl.getString(editText))) {
                    return true;
                } else {
                    showShortSnackBar(this, "请输入正确的手机号");
                    return false;
                }
            } else {
                if (TextUitl.isEmail(TextUitl.getString(editText))) {
                    return true;
                } else {
                    showShortSnackBar(this, "请输入正确的邮箱号");
                    return false;
                }
            }
        }
    }


    /**
     * 验证新输入账户
     *
     * @return
     */
    private boolean isEqualsPhone() {
        if (TextUitl.getString(changephone_end).equals(TextUitl.getString(changephone_new))) {
            ToastUtils.showShortSnackBar(this, "请输入与原号码不同的号码");
            return false;
        }
        return true;

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        timeCount.cancel();
    }


}
